package main

import (
	"crypto/md5"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"mxshop_srvs/user_srv/model"
	"os"
	"strconv"
	"time"
)

func genMd5(code string) string {
	sum := md5.Sum([]byte(code))
	return hex.EncodeToString(sum[:])
}

func autoMigrate() {
	//配置sql日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // 日志级别
			Colorful:      true,        // 禁用彩色打印
		},
	)

	dsn := "root:123456@tcp(127.0.0.1:3306)/mxshop_user_srv?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{SingularTable: true},
		Logger:         newLogger,
	})
	if err != nil {
		log.Printf("数据库连接失败,%v\n", err)
		return
	}

	options := &password.Options{SaltLen: 10, Iterations: 100, KeyLen: 32, HashFunction: sha512.New}
	salt, encodedPwd := password.Encode("admin", options)
	encodedPwd = fmt.Sprintf("pbkdf2-sha512$%s$%s", salt, encodedPwd)
	for i := 0; i < 10; i++ {
		strID := strconv.Itoa(i)
		user := model.User{
			Mobile:   "1713623745" + strID,
			NickName: "lshsh" + strID,
			Password: encodedPwd,
		}
		db.Save(&user)
	}

	//err = db.AutoMigrate(&model.User{})
	//if err != nil {
	//	log.Printf("生成迁移数据失败,%v\n", err)
	//}
}

func main() {
	//fmt.Println(genMd5("123456"))

	autoMigrate()
	//options := &password.Options{SaltLen: 10, Iterations: 100, KeyLen: 32, HashFunction: sha512.New}
	//salt, encodedPwd := password.Encode("generic password", options)
	//encodedPwd = fmt.Sprintf("pbkdf2-sha512$%s$%s", salt, encodedPwd)
	//passwordInfo := strings.Split(encodedPwd, "$")
	//check := password.Verify("generic password", passwordInfo[1], passwordInfo[2], options)
	//fmt.Println(check) // true
}
